package com.zaoqi.controller;

import com.zaoqi.service.GraphService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/graph", produces = "application/json;charset=UTF-8")
public class GraphController {

    @Autowired
    private GraphService graphService;

    // 导入实体节点
    @PostMapping("/entities")
    public String importEntities(@RequestBody List<String> labels) {
        if (labels == null || labels.isEmpty()) {
            throw new IllegalArgumentException("Labels list cannot be null or empty");
        }
        String label = "DefaultLabel"; // 可替换为动态标签
        List<Map<String, Object>> entities = labels.stream()
                .map(name -> {
                    Map<String, Object> entity = new HashMap<>();
                    entity.put("label", name);
                    entity.put("createdAt", LocalDateTime.now().toString());
                    return entity;
                })
                .toList();

        graphService.batchImportEntities(label, entities);
        return "实体批量导入成功";
    }

    @PostMapping("/relationships")
    public String importRelationships(
            @RequestBody List<Map<String, Object>> relationships) {
        if (relationships == null || relationships.isEmpty()) {
            throw new IllegalArgumentException("Relationships list cannot be null or empty");
        }
        System.out.println("Processing relationships: " + relationships);
        for (Map<String, Object> relationship : relationships) {
            try {
                // 提取关系信息
                String fromLabel = (String) relationship.get("from"); // 使用 `from` 匹配实体的 label
                String toLabel = (String) relationship.get("to");     // 使用 `to` 匹配实体的 label
                String relationshipType = (String) relationship.get("Relationship");

                if (fromLabel == null || toLabel == null || relationshipType == null) {
                    throw new IllegalArgumentException("Relationship details are incomplete: " + relationship);
                }
                // 基于 label 匹配的逻辑
                graphService.importRelationshipByLabels(fromLabel, toLabel, relationshipType);
            } catch (Exception e) {
                System.err.println("Failed to import relationship: " + relationship);
                e.printStackTrace();
            }
        }
        return "关系批量导入成功";
    }


    // 搜索接口
    @GetMapping("/search")
    public List<Map<String, Object>> searchGraph(@RequestParam String keyword) {
        return graphService.searchNodes(keyword);
    }

}
